
using UnityEditor;
using UEditor = UnityEditor.Editor;

namespace LS.UnityExtensions.Editor
{
    public abstract class InspectorBase : UEditor
    {
        protected SerializedProperty m_Script;

        protected virtual bool DrawCustomInspector
        {
            get
            {
                return true;
            }
        }

        protected virtual bool ShowScriptProperty
        {
            get
            {
                return true;
            }
        }
        
        protected virtual void OnEnable()
        {
            m_Script = serializedObject.FindProperty("m_Script");
        }

        protected virtual void OnDisable()
        {

        }

        public override void OnInspectorGUI()
        {
            DrawInspectorStart();
            if (DrawCustomInspector)
            {
                if(DoDrawInspector(serializedObject, DrawInspector))
                {
                    OnPropertyValueChanged();
                    Repaint();
                }
            }
            else
            {
                if (DrawDefaultInspector())
                {
                    OnPropertyValueChanged();
                    Repaint();
                }
            }

            DrawInspectorLate();
            DrawInspectorFinish();
        }

        internal static bool DoDrawInspector(SerializedObject obj, System.Action drawInspectorItem)
        {
            EditorGUI.BeginChangeCheck();
            obj?.UpdateIfRequiredOrScript();
            drawInspectorItem?.Invoke();
            obj?.ApplyModifiedProperties();
            return EditorGUI.EndChangeCheck();
        }

        private void DrawInspector()
        {
            if (ShowScriptProperty)
            {
                using (new EditorGUI.DisabledScope(true))
                    EditorGUILayout.PropertyField(m_Script);
            }

            DrawInspectorItems();
            DrawInspectorMessage();
        }

        public virtual void DrawInspectorItems() { }
        public virtual void DrawInspectorLate(){ }
        public virtual void DrawInspectorStart() { }
        public virtual void DrawInspectorFinish() { }
        public virtual void DrawInspectorMessage() { }
        public virtual void OnPropertyValueChanged() { }

        protected SerializedProperty FindProperty(string name)
        {
            return serializedObject.FindProperty(name);
        }
    }
}
